//
//  WorkStartViewController.swift
//  vmes
//
//  Created by user on 2021/10/28.
//

import UIKit
import Alamofire

class WorkStartViewController: BaseController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    let top=UIView()
    let planNum=UILabel()
    let alreadyNum=UILabel()
    let waitNum=UILabel()
    
    var orderInfo:OrderItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.tintColor = .black
        self.navigationItem.title="工单开工"
        self.view.backgroundColor = .white
        top.backgroundColor=UIColor.colorWithHex(hexStr: "#E3E5E7")
        top.layer.cornerRadius=10
        view.addSubview(top)
        top.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(statusBarHeight)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(300)
        }
        let orderNoLb=UILabel()
        orderNoLb.text="orderNo"
        let desc1Lb=UILabel()
        let desc2Lb=UILabel()
        let statusLb=UILabel()
        statusLb.text="生产中"
        let planStartLb=UILabel()
        planStartLb.text="计划开始"
        let realStartLb=UILabel()
        realStartLb.text="实际开始"
        let planStopLb=UILabel()
        planStopLb.text="计划结束"
        let realStopLb=UILabel()
        realStopLb.text="实际结束"
        let planStart=UILabel()
        planStart.font = .systemFont(ofSize: 14)
        let planStop=UILabel()
        planStop.font = .systemFont(ofSize: 14)
        let realStart=UILabel()
        realStart.font = .systemFont(ofSize: 14)
        let realStop=UILabel()
        realStop.font = .systemFont(ofSize: 14)
        let materialTxt=UILabel()
        let materialColor=UILabel()
        materialTxt.font = .systemFont(ofSize: 14)
        materialColor.font = .systemFont(ofSize: 14)
        [orderNoLb,statusLb,desc1Lb,desc2Lb,planStop,planStart,
         planStopLb,planStartLb,realStop,realStart,realStopLb,realStartLb,materialTxt,materialColor].forEach {
            top.addSubview($0)
        }
        materialTxt.text="物料材质：" + (orderInfo?.materialText ?? "空")
        materialColor.text="物料颜色：" + (orderInfo?.materialColo ?? "无")
        orderNoLb.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(20)
        }
        materialTxt.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(orderNoLb.snp.bottom).offset(10)
        }
        materialColor.snp.makeConstraints { make in
            make.left.equalTo(materialTxt.snp.right).offset(10)
            make.top.equalTo(materialTxt.snp.top)
        }
        desc1Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(materialTxt.snp.bottom).offset(10)
        }
        desc2Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(desc1Lb.snp.bottom)
        }
        statusLb.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(orderNoLb.snp.top)
        }
        let line=UIView()
        line.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        top.addSubview(line)
        line.snp.makeConstraints { make in
            make.height.equalTo(0.5)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.centerX.equalTo(top.snp.centerX)
            make.top.equalTo(desc2Lb.snp.bottom)
                .offset(15)
        }
        //计划
        planStartLb.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(15)
            make.left.equalTo(orderNoLb.snp.left)
        }
        planStart.snp.makeConstraints { make in
            make.top.equalTo(planStartLb.snp.bottom).offset(10)
            make.left.equalTo(planStartLb.snp.left)
        }
        planStopLb.snp.makeConstraints { make in
            make.top.equalTo(planStart.snp.bottom).offset(40)
            make.left.equalTo(planStartLb.snp.left)
        }
        planStop.snp.makeConstraints { make in
            make.top.equalTo(planStopLb.snp.bottom).offset(10)
            make.left.equalTo(planStopLb.snp.left)
        }
        //实际
        realStartLb.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(15)
            make.left.equalTo(top.snp.centerX).offset(10)
        }
        realStart.snp.makeConstraints { make in
            make.top.equalTo(realStartLb.snp.bottom).offset(10)
            make.left.equalTo(realStartLb.snp.left)
        }
        realStopLb.snp.makeConstraints { make in
            make.top.equalTo(realStart.snp.bottom).offset(40)
            make.left.equalTo(realStartLb.snp.left)
        }
        realStop.snp.makeConstraints { make in
            make.top.equalTo(realStopLb.snp.bottom).offset(10)
            make.left.equalTo(realStartLb.snp.left)
        }
        //绑定数据
        orderNoLb.text=orderInfo?.workorderCode
        desc1Lb.text=orderInfo?.productCode ?? "暂无产品内容"
        desc2Lb.text=orderInfo?.productName ?? "暂无产品内容"
        if("0"==orderInfo?.statusFlag!){
            statusLb.text="待生产"
        }else if("1"==orderInfo?.statusFlag!){
            statusLb.text="当班开工"
        }else if("2"==orderInfo?.statusFlag!){
            statusLb.text="当班完工"
        }else if("3"==orderInfo?.statusFlag!){
            statusLb.text="已完成"
        }
        planStart.text=orderInfo?.planStartTime ?? "无"
        planStop.text=orderInfo?.planEndTime ?? "无"
        realStart.text=orderInfo?.actualStartTime ?? "无"
        realStop.text=orderInfo?.actualEndTime ?? "无"
        
        initNumLabel()
        initBtnArea()
        getErpInfo()
    }
    
    func initNumLabel(){
        let planNumLb=UILabel()
        let allNumLb=UILabel()
        let waitNumLb=UILabel()
        planNumLb.text="总排产量"
        allNumLb.text="已报工量"
        waitNumLb.text="当班计划量"
        
        [planNumLb,allNumLb,waitNumLb].forEach({
            view.addSubview($0)
            $0.textAlignment = .center
            $0.textColor=UIColor.colorWithHex(hexStr: "#333333")
            $0.font = UIFont.systemFont(ofSize: 15)
        })
        planNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
        }
        allNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(planNumLb.snp.right)
        }
        waitNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(allNumLb.snp.right)
        }
        [planNum,alreadyNum,waitNum].forEach({
            view.addSubview($0)
            $0.textAlignment = .center
            $0.text="500"
            $0.textColor=UIColor.colorWithHex(hexStr: "#0FA386")
            $0.font = UIFont.systemFont(ofSize: 20)
        })
        planNum.snp.makeConstraints { make in
            make.centerX.equalTo(planNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        alreadyNum.snp.makeConstraints { make in
            make.centerX.equalTo(allNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        waitNum.snp.makeConstraints { make in
            make.centerX.equalTo(waitNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        planNum.text=String(orderInfo?.scheduleNumber ?? 0)
        alreadyNum.text=String(orderInfo?.workreportOutput ?? 0)
        waitNum.text=String(orderInfo?.shiftPlanOutput ?? 0)
    }
    
    func initBtnArea(){
        let area=UIView()
        area.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        view.addSubview(area)
        area.snp.makeConstraints { make in
            make.top.equalTo(planNum.snp.bottom).offset(40)
            make.left.right.bottom.equalToSuperview()
        }
        let inner=UIView()
        inner.backgroundColor = .white
        area.addSubview(inner)
        inner.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview().offset(-50)
            //            make.width.equalTo(width-30)
            make.height.equalTo(200)
        }
        inner.layer.cornerRadius=10
        inner.layer.masksToBounds=true
        //创建图层
        //        let shapeLayer:CAShapeLayer = CAShapeLayer()
        //        shapeLayer.path = UIBezierPath.init(roundedRect: inner.bounds, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: CGSize(width: 10, height: 10)).cgPath
        
        //为view指定图层
        //        inner.layer.mask = shapeLayer
        
        //设置背景色便于观察
        //        view.backgroundColor = UIColor.red
        
        
        //        inner.roundCorners([.topLeft,.topRight], radius: 10)
        let btn=UIButton()
        let wlBtn=UIButton()
        btn.layer.cornerRadius=5
        wlBtn.layer.cornerRadius=5
        inner.addSubview(btn)
        inner.addSubview(wlBtn)
        
        wlBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(55)
        }
        btn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(wlBtn.snp_bottom).offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(55)
        }
        btn.setTitle("提交开工信息", for: .normal)
        wlBtn.setTitle("物料送达", for: .normal)
        btn.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btn.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        btn.addTarget(self, action: #selector(showConfrimAlert), for: .touchUpInside)
        
        wlBtn.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        wlBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        wlBtn.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        wlBtn.addTarget(self, action: #selector(openBottomDialog), for: .touchUpInside)
    }
    
    @objc func showConfrimAlert(){
        let alertView = UIAlertController.init(title: "提示", message: "确认开工么", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "确定", style: .destructive) { (UIAlertAction) in
            self.openWork()
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            print("点击取消按钮")
        }
        alertView.addAction(cancleAlert)
        alertView.addAction(alert);
        self.present(alertView, animated: true, completion: nil)
    }
    
    @objc func openBottomDialog(){
        let alert: UIAlertController!
        alert = UIAlertController(title: "", message: "请选择工单对应操作", preferredStyle: .actionSheet)
        let cleanAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        //        UIImagePickerController.
        let camera = UIAlertAction(title: "相机", style: .default, handler: {action in self.openCamera()})
        let photo = UIAlertAction(title: "图库", style: .default, handler: {action in self.openPhoto()})
        
        alert.addAction(camera)
        alert.addAction(photo)
        alert.addAction(cleanAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func openCamera(){
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let pickerVC = UIImagePickerController()
            pickerVC.delegate = self
            pickerVC.sourceType = UIImagePickerController.SourceType.camera
            self.present(pickerVC, animated: true, completion: nil)
        } else {
            print("------> ERROR")
        }
        
        
    }
    
    @objc func openPhoto(){
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            //创建图片选择控制器
            let pickerVC = UIImagePickerController()
            pickerVC.delegate = self
            
            // 设置源为相机
            pickerVC.sourceType = UIImagePickerController.SourceType.photoLibrary
            self.present(pickerVC, animated: true, completion: nil)
        } else {
            print("------> ERROR")
        }
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.delegate = nil
        print("------> INFO:\(info)")
        let image: UIImage!
        image = info[.originalImage] as? UIImage
        //                self.imageView.image = image
        picker.dismiss(animated: true,completion: nil)
        print("choose")
        upLoadImage(imageData: image)
    }
    
    func upLoadImage(imageData:UIImage){
        spinner.startAnimating()
        AF.upload(multipartFormData: { multipartFormData in
            //            let _data = UIImage.loadData(imageData)
            let _data=imageData.jpegData(compressionQuality: 1)
            multipartFormData.append(_data!, withName: "file", fileName: "file", mimeType: "image/png")
            let scheduleNumber:String = self.orderInfo?.id ?? ""
            let userId=K.userInfo?.userId ?? ""
            multipartFormData.append(userId.data(using: .utf8)!, withName: "user")
            multipartFormData.append(scheduleNumber.data(using: .utf8)!, withName: "scheduleId")
            
        }, to: NetInfo.upLoad).responseJSON { (response) in
            self.spinner.stopAnimating()
            debugPrint(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.view.makeToast("上传成功",duration:2)
                        //                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
        
    }
    
    func getErpInfo(){
        spinner.startAnimating()
        let parameters: Dictionary = [
            "compId" : K.userInfo?.company?.companyId!,
            "workorderCode" : orderInfo?.workorderCode!,
        ]
        AF.request(NetInfo.checkOrderLL, method:.post
                   , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 5 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let status = try? JSONDecoder().decode(Int.self, from: data)
                    if status != nil{
                        if(status == 2){
                            let alertView = UIAlertController.init(title: "提示", message: "请去ERP领料", preferredStyle: .alert)
                            let alert = UIAlertAction.init(title: "确定", style: .destructive) { (UIAlertAction) in
                                alertView.dismiss(animated: true)
                            }
                            alertView.addAction(alert);
                            self.present(alertView, animated: true, completion: nil)
                            
                        }
                        
                    }
                }
               
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    @objc func openWork(){
        print("开工")
        spinner.startAnimating()
        let parameters: Dictionary = [
            "compId" : K.userInfo?.company?.companyId!,
            "startOperator" : K.userInfo?.userId!,
            "shiftPlanOutput" : String(orderInfo?.shiftPlanOutput ?? 0),
            "workorderCode" : orderInfo?.workorderCode!,
            "workshopId" : K.currentWorkShop?.workshopId!,
            "scheduleId":orderInfo?.id!
        ]
        AF.request(NetInfo.startWork, method:.post
                   , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 5 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.view.makeToast("开工成功",duration:2)
                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
}
